package com.weirong.smartvault.backservice.controller;

import com.weirong.smartvault.backservice.controller.fragment_entity.PagesIndex;
import com.weirong.smartvault.backservice.service.CashboxRealtimeService;
import com.weirong.smartvault.common.tools.constant.DepartmentType;
import com.weirong.smartvault.backservice.entity_model.*;
import com.weirong.smartvault.common.tools.constant.ThymleafVarName;
import com.weirong.smartvault.dao.*;
import com.weirong.smartvault.entity.*;
import com.weirong.smartvault.backservice.service.DepartmentService;
import com.weirong.smartvault.backservice.service.DictService;
import com.weirong.smartvault.backservice.util.common.ListTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by KFEB4 on 2017/11/16.
 */
@Controller
@RequestMapping(value = "/base")
public class Base {
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private DictRepository dictRepository;
    @Autowired
    private DictService dictService;

    @Autowired
    private AreaRepository areaRepository;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private CashboxRealtimeService cashboxRealtimeService;

    @Autowired
    private CashboxUnitRepository cashboxUnitRepository;

    @Autowired
    private ForeignCurrencyTypeRepository foreignCurrencyTypeRepository;

    @Autowired
    private ForeignCurrencyDenominationRepository foreignCurrencyDenominationRepository;

    @Autowired
    private RouteRepository routeRepository;
    @RequestMapping(value = "/add_org", method = RequestMethod.GET)
    public String addOrgGet(ModelMap model, @RequestParam(value = "id", defaultValue = "-1") Integer id) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        DepartmentModel department;
        if (id > 0) {
            department = new DepartmentModel(departmentRepository.findOne(id));
        } else {
            department = new DepartmentModel(new Department());
        }
        model.addAttribute("goal", department);
        departmentService.setModelDepartmentAreaSelected(department, model);

        List<Dict> categorys = new ArrayList<>();
        categorys.add(dictRepository.findByName(DepartmentType.fh));
        categorys.add(dictRepository.findByName(DepartmentType.zh));
        categorys.add(dictRepository.findByName(DepartmentType.wd));
        ListTool.moveToTop(categorys, department.getTypeDict());
        model.addAttribute(ThymleafVarName.Var.categorys, categorys);

        List<Route> routes = routeRepository.findAll();
        ListTool.moveToTop(routes,department.getRoute());
        model.addAttribute(ThymleafVarName.Var.routes,ListTool.cast(routes,RouteModel.class));

        model.addAttribute(ThymleafVarName.Var.superiorDepartments, departmentService.getSuperiorDepartments(department));

        return "base/add_org";
    }

    @RequestMapping(value = "/add_org", method = RequestMethod.POST)
    public String addOrgPost(ModelMap model, Department department, @RequestParam(value = "id", defaultValue = "-1") Integer id) {

        departmentRepository.save(department);
        return "redirect:/base/add_org";//返回空白页面
    }

    @RequestMapping(value = "/org")
    public String orgGet(ModelMap model, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        Page<Department> departmentPage = departmentRepository.findAll(pageable);
        List<DepartmentModel> departments = new ArrayList<>();
        for (Department department : departmentPage) {
            departments.add(new DepartmentModel(department));
        }
        model.addAttribute("departments", departments);

        model.addAttribute(ThymleafVarName.pages, new PagesIndex(page, departmentPage.getTotalPages()));

        return "base/org";
    }

    @RequestMapping(value = "/dict")
    public String dictGet(ModelMap model, @RequestParam(value = "page", defaultValue = "0") Integer page,
                          @RequestParam(value = "size", defaultValue = "10") Integer size,
                          @RequestParam(value = "marks", defaultValue = "") String marks) {
        //marks 拓展标记
        Page<Dict> dicts = dictService.findAllRootPageable(page, size);
        List<DictModel> dts = new ArrayList<>();
        for (Dict dict : dicts) {
            DictModel td = new DictModel(dict, marks);
            dts.add(td);
            dts.addAll(td.getSonDict());
        }
        model.addAttribute("dicts", dts);

        model.addAttribute(ThymleafVarName.pages, new PagesIndex(page, dicts.getTotalPages()));

        return "base/dict";
    }

    @RequestMapping(value = "/dict", method = RequestMethod.POST)
    public String addDict(ModelMap model, Dict dict, @RequestParam(value = "page", defaultValue = "0") Integer page,
                          @RequestParam(value = "size", defaultValue = "10") Integer size,
                          @RequestParam(value = "marks", defaultValue = "") String marks) {
        if (dict.getParentId() < 0)
            dict.setParentId(null);
        dictRepository.save(dict);
        return dictGet(model, page, size, marks);
    }

    @RequestMapping(value = "/box", method = RequestMethod.GET)
    public String boxGet(ModelMap model, @RequestParam(value = "page", defaultValue = "0") Integer page,
                         @RequestParam(value = "size", defaultValue = "10") Integer size,
                         @RequestParam(value = "unitNo", defaultValue = "1") Integer unitNo) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        Page<CashboxRealtime> cashboxConf = cashboxRealtimeService.findAllByUnitNoWithPaging(unitNo,page,size);

        model.addAttribute(ThymleafVarName.Var.cashboxConfs,ListTool.cast(cashboxConf, CashboxRealtimeModel.class));

        model.addAttribute(ThymleafVarName.pages,new PagesIndex(page,cashboxConf.getTotalPages(), "unitNo",unitNo.toString()));

        List<CashboxUnit> cashboxUnits = cashboxUnitRepository.findAll();
        ListTool.moveToTop(cashboxUnits,cashboxUnitRepository.getOne(unitNo));
        model.addAttribute(ThymleafVarName.Var.cashboxUnits,ListTool.cast(cashboxUnits, CashboxUnitModel.class));
        return "base/box";
    }

    @RequestMapping(value = "/box_unit",method = RequestMethod.GET)
    public String boxUnitGet(ModelMap model) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        List<CashboxUnit> cashboxUnits = cashboxUnitRepository.findAll();
        model.addAttribute(ThymleafVarName.Var.cashboxUnits,ListTool.cast(cashboxUnits,CashboxUnitModel.class));
        return "base/box_unit";
    }
    @RequestMapping(value = "/box_unit",method = RequestMethod.POST)
    public String boxUnitPost(ModelMap model, CashboxUnit cashboxUnit) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        cashboxUnitRepository.save(cashboxUnit);
        return boxUnitGet(model);
    }
    @RequestMapping(value = "/foreign_currency_type",method = RequestMethod.GET)
    public String foreignCurrencyTypeGet(ModelMap model) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        List<ForeignCurrencyType> foreignCurrencyTypes= foreignCurrencyTypeRepository.findAll();
        model.addAttribute(ThymleafVarName.Var.foreignCurrencyTypes,ListTool.cast(foreignCurrencyTypes, ForeignCurrencyTypeModel.class));
        return "base/foreign_currency_type";
    }
    @RequestMapping(value = "/foreign_currency_type",method = RequestMethod.POST)
    public String foreignCurrencyTypePost(ModelMap model,ForeignCurrencyType foreignCurrencyType) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        foreignCurrencyTypeRepository.save(foreignCurrencyType);
        return foreignCurrencyTypeGet(model);
    }

    @RequestMapping(value = "/denomination",method = RequestMethod.GET)
    public String denominationGet(ModelMap model,@RequestParam(value =ThymleafVarName.QuestVar.typeCode,defaultValue = "")String typecode) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        List<ForeignCurrencyType> tps =foreignCurrencyTypeRepository.findAll();
        if (typecode.length()>0) {
            ForeignCurrencyType selected = foreignCurrencyTypeRepository.getByCode(typecode);
            if (selected!=null)
                ListTool.moveToTop(tps,selected);
        }
        List<ForeignCurrencyTypeModel> foreignCurrencyTypes = ListTool.cast(tps,ForeignCurrencyTypeModel.class);
        if(typecode.length() ==0){
            typecode = foreignCurrencyTypes.get(0).getCode();
        }
        model.addAttribute(ThymleafVarName.Var.foreignCurrencyTypes,foreignCurrencyTypes);
        List<ForeignCurrencyDenomination> foreignCurrencyDenominations = foreignCurrencyDenominationRepository.getForeignCurrencyDenominationByTypeCode(typecode);
        model.addAttribute(ThymleafVarName.Var.foreignCurrencyDenominations,ListTool.cast(foreignCurrencyDenominations,ForeignCurrencyDenominationModel.class));

        return "base/denomination";
    }
    @RequestMapping(value = "/denomination",method = RequestMethod.POST)
    public String denominationPost(ModelMap model,ForeignCurrencyDenomination foreignCurrencyDenomination,@RequestParam(value =ThymleafVarName.QuestVar.typeCode,defaultValue = "")String typecode) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        foreignCurrencyDenominationRepository.save(foreignCurrencyDenomination);
        return denominationGet(model,typecode);
    }

}
